const app = getApp();
const { AskComponent } = app._require("common/index");
const amapFile = app._require("libs/amap-wx.js");
// import { merge } from "../../utils/index";

// 正式key
const myAmapFun = new amapFile.AMapWX({ key: "48f46ec834b60311104b1073c42bbf7f" });
// 测试使用的key
// const myAmapFun = new amapFile.AMapWX({ key: "e8c65f0c22b26df604888b4ff3b61ce8" });
AskComponent({
    properties: {
        model: {
            type: Object,
            value: {},
            observer: "observeModel",
        },
        requiredVal: {
            type: Boolean,
            value:false
        }
    },
    data: {
        options: {
            locationLabel: "所在地址",
            locationPlaceholder: "请选择定位",
            townVillageLabel: "镇村",
            townVillagePlaceholder: "请选择镇村",
            addressLabel: "详细地址",
            addressPlaceholder: "请输入xx镇xx村xx组xx号",
            addressModel: "show", // 空代表不展示
            addressDataModel: "show", // 是否展示经纬度按钮空代表不展示
            addressDataText: "地址定位", // 经纬度按钮默认文字
            parseBtnModel: "show", // 空代表不展示
            parseBtnText: "编辑经纬度",
            locationModel: "area", // 省市区镇 province、city、area、town
            townVillageModel: "village", // 镇 区  town village ""空代表不展示
            before: () => Promise.resolve(true),
            customCityInfo: () => Promise.resolve(true),
        },
        popupModel: {
            latitude: "",
            longitude: "",
            cityInfo: "",
            cityCode: "",
            town: "",
            townCode: "",
        },
        oldCityCode: "",
    },
    lifetimes: {
        attached() {
            // 在组件实例进入页面节点树时执行
        },
        detached() {
            // 在组件实例被从页面节点树移除时执行
        },
    },
    ready() {},
    methods: {
        observeModel(now, old) {
            // console.log("now,old", now, old);
            if(!now){return}
            if (now.cityCode || "" && now.cityCode || "" === old.cityCode || "") {
                return;
            }
            if (this.data.oldCityCode !== this.data.model.cityCode || this.data.model.cityCode === "") {
                const { latitude = "", longitude = "" } = this.data.model;
                if (latitude && longitude) {
                    this.modelParseAddress(this.data.model, "地址解析中");
                    this.data.oldCityCode = this.data.model.cityCode || "";
                }
            }
        },
        async submit() {
            const info = this.checkInfo();
            return Promise.resolve({
                result: info.result,
                msg: info.msg,
            });
        },
        checkInfo() {
            const address = this.data.model;
            if (this.data.options.locationModel === "town" ? !address.townCode : !address.cityCode) {
                return {
                    result: false,
                    msg: "请选择定位！",
                };
            }
            if (!address.info) {
                return {
                    result: false,
                    msg: "请输入xx镇xx村xx组xx号！",
                };
            }
            return {
                result: true,
                msg: "",
            };
        },
        setModel(e) {
            this.$emit("setModel", e);
        },
        parseInfoAddress(keywords) {
            return new Promise((resolve, reject) => {
                myAmapFun.getInputtips({
                    keywords,
                    success: res => {
                        resolve(res);
                    },
                    fail: res => {
                        wx.askShowToastEx({
                            mask: true,
                            duration: 2000,
                            icon: "none",
                            title: "获取定位失败，errCode:" + res.errCode,
                            callback: () => {
                                reject();
                            },
                        });
                    },
                });
            });
        },
        parseAddress(address) {
            return new Promise((resolve, reject) => {
                // latitude  number  纬度，范围为 -90~90，负数表示南纬
                // longitude number  经度，范围为 -180~180，负数表示西经
                const { latitude = "", longitude = "" } = address;
                myAmapFun.getRegeo({
                    location: longitude + "," + latitude,
                    success: async res => {
                        console.log("res", res[0]);
                        if (!res[0]) {
                            wx.askShowToastEx({
                                mask: true,
                                duration: 2000,
                                icon: "none",
                                title: "获取定位失败",
                                callback: () => {
                                    reject();
                                },
                            });
                            return;
                        }
                        if (!res[0].desc && !res[0].name) {
                            wx.askShowToastEx({
                                mask: true,
                                duration: 2000,
                                icon: "none",
                                title: "请输入正确的经纬度",
                                callback: () => {
                                    reject();
                                },
                            });
                            return;
                        }
                        const { options } = this.data;
                        const _data = res[0];
                        const _regeocodeData = _data.regeocodeData;
                        let showModel = [
                            {
                                key: "province",
                                parseKey: "province",
                            },
                            {
                                key: "city",
                                parseKey: "city",
                            },
                            {
                                key: "area",
                                parseKey: "district",
                            },
                            {
                                key: "town",
                                parseKey: "township",
                            },
                        ];
                        const _index = showModel.findIndex(cur => cur.key === options.locationModel);
                        showModel = showModel.slice(0, _index + 1);
                        const _cityInfo = showModel.map(cur => _regeocodeData.addressComponent[cur.parseKey]);
                        const model = {
                            cityInfo: _cityInfo.join(""),
                            cityCode: _regeocodeData.addressComponent.adcode || "",
                            town: _regeocodeData.addressComponent.township || "",
                            townCode: _regeocodeData.addressComponent.towncode || "",
                            latitude,
                            longitude,
                        };
                        resolve(model);
                    },
                    fail: res => {
                        wx.askShowToastEx({
                            mask: true,
                            duration: 2000,
                            icon: "none",
                            title: "获取定位失败，errCode:" + res.errCode,
                            callback: () => {
                                reject();
                            },
                        });
                    },
                });
            });
        },
        async getLocation() {
            const beforeResponse = await this.data.options.before();
            if (!beforeResponse) return;
            const initLocation = ()=>{
                wx.chooseLocation({
                    success: res => {
                        // latitude  number  纬度，范围为 -90~90，负数表示南纬
                        // longitude number  经度，范围为 -180~180，负数表示西经
                        this.modelParseAddress(res, "定位中");
                    },
                    fail() {
                        wx.hideLoading();
                    },
                });
            }
            wx.getSetting({
                success: sRes => {
                    console.log(sRes.authSetting);
                    if (!sRes.authSetting["scope.userLocation"]) {
                        wx.authorize({
                            scope: "scope.userLocation",
                            success: aRes => {
                                console.log("aRes", aRes);
                                initLocation();
                            },
                            fail: aErr => {
                                wx.hideLoading();
                                wx.showModal({
                                    title: "温馨提示",
                                    content: "请先开启定位授权哦",
                                    success(res) {
                                        if (res.confirm) {
                                            wx.openSetting({
                                                success(oRes) {
                                                    if (!oRes.authSetting["scope.userLocation"]) {
                                                        wx.askShowToastEx({
                                                            icon: "none",
                                                            title: "请开启定位授权!",
                                                        });
                                                    }
                                                },
                                            });
                                        } else if (res.cancel) {
                                            wx.askShowToastEx({
                                                icon: "none",
                                                title: "请开启定位授权!",
                                            });
                                        }
                                    },
                                });
                            },
                        });
                    }
                    if (sRes.authSetting["scope.userLocation"]) {
                        initLocation();
                    }
                },
            });
        },
        modelParseAddress(res, loadText = "处理中") {
            wx.showLoading({
                title: loadText,
                mask: true,
            });
            return this.parseAddress({ latitude: res.latitude, longitude: res.longitude })
                .then(res => {
                    wx.hideLoading();
                    const villageObj = {};
                    // console.log(this.data.model);

                    let cityCode = ""
                    if(this.data.model){
                        cityCode =  this.data.model.cityCode || "";
                    }

                    if (cityCode !== res.cityCode||"") {
                        villageObj.townVillageValue = "";
                        villageObj.townVillageText = "";
                        this.selectComponent("#ask_select") && this.selectComponent("#ask_select").clear();
                    }
                    this.setModel({
                        currentTarget: {
                            dataset: {
                                key: "address",
                            },
                        },
                        detail: {
                            value: {
                                ...this.data.model,
                                ...res,
                                ...villageObj,
                            },
                        },
                    });
                })
                .catch(error => {
                    wx.hideLoading();
                    throw error;
                });
        }
    },
});
